<?php

namespace controller\admin;

defined('IA_ROOT') || exit();

use mvc\Controller;
use facade\Model;
use facade\View;
use facade\Util;

class Base extends Controller
{
    // 基址
    protected $site_url;
    protected $subdir;

    // 用户角色权限
    protected $user;
    protected $role;
    protected $auth;

    // 模块控制器方法
    protected $module;
    protected $controller;
    protected $action;

    // 系统设置
    protected $setting;

    // 初始化
    protected function initialize()
    {
        // 登录认证
        !session_id() && session_start();
        $this->site_url = Util::url();
        $this->subdir = Util::subdir();
        $ip = Util::getIp();
        if (!isset($_SESSION['uid']) || empty($_SESSION['uid'])) {
            if (!isset($_COOKIE['token']) || empty($_COOKIE['token'])) {
                Util::config('log') && Model::insert('log', ['author' => '匿名', 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '非法访问', 'message' => '未登录访问后台', 'ip' => $ip, 'status' => 1, 'time' => time()]);
                Util::errMsg(['code' => 1, 'msg' => '请先登录', 'url' => Util::url('/admin/login.html')]);
            }
            $this->user = Model::fetch("SELECT * FROM `user` WHERE `remember_token`=:token ORDER BY `id` ASC LIMIT 1", [':token' => $_COOKIE['token']]);
            if (!$this->user) {
                Util::config('log') && Model::insert('log', ['author' => '匿名', 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '非法访问', 'message' => 'Cookie无效或过期', 'ip' => $ip, 'status' => 1, 'time' => time()]);
                Util::errMsg(['code' => 1, 'msg' => '请先登录', 'url' => Util::url('/admin/login.html')]);
            }
            $_SESSION['uid'] = $this->user['id'];
        }
        if (!$this->user) {
            $this->user = Model::fetch("SELECT * FROM `user` WHERE `id`=:id ORDER BY `id` ASC LIMIT 1", [':id' => $_SESSION['uid']]);
        }
        if (!$this->user) {
            Util::config('log') && Model::insert('log', ['author' => '匿名', 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '非法访问', 'message' => 'Session无效或过期', 'ip' => $ip, 'status' => 1, 'time' => time()]);
            Util::errMsg(['code' => 1, 'msg' => '请先登录', 'url' => Util::url('/admin/login.html')]);
        }

        // 检查单点登录
        $this->setting = $this->setting();
        if ($this->setting['alone_login']) {
            $randstr = isset($_COOKIE['randstr']) ? $_COOKIE('randstr') : false;
            $cache_randstr = Util::getCache('rand' . $this->user['id']);
            if ($randstr !== $cache_randstr) {
                unset($_SESSION['uid']);
                setcookie('token', '', time() - 3600, '/');
                Util::errMsg(['code' => 1, 'msg' => '您的账号已在别处登录，请重新登录！', 'url' => Util::url('/admin/login.html')]);
            }
        }

        // 获取当前模块-控制器-方法
        $this->module = Util::module();
        $this->controller = Util::controller();
        $this->action = Util::action();

        // 用户-角色-权限认证
        $this->role = Model::fetchAll("SELECT * FROM `role` ORDER BY `sort` DESC, `id` ASC");
        $this->auth = Model::fetchAll("SELECT * FROM `auth` ORDER BY `sort` DESC, `id` ASC");
        $_role = array_filter($this->role, function ($item) {
            return $item['id'] === $this->user['role_id'];
        });
        $_role = array_shift($_role);
        if (!$_role) {
            Util::config('log') && Model::insert('log', ['author' => $this->user['username'], 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '拒绝访问', 'message' => '角色不存在', 'ip' => $ip, 'status' => 1, 'time' => time()]);
            Util::errMsg('角色不存在，请联系管理员');
        }
        if (1 == $_role['status']) {
            Util::config('log') && Model::insert('log', ['author' => $this->user['username'], 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '拒绝访问', 'message' => '角色被禁用', 'ip' => $ip, 'status' => 1, 'time' => time()]);
            Util::errMsg('角色被禁用，请联系管理员');
        }
        $_auth = array_filter($this->auth, function ($item) {
            return $item['controller'] === $this->controller && $item['action'] === $this->action;
        });
        $_auth = array_shift($_auth);
        if (!$_auth) {
            Util::config('log') && Model::insert('log', ['author' => $this->user['username'], 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '拒绝访问', 'message' => '功能不存在', 'ip' => $ip, 'status' => 1, 'time' => time()]);
            Util::errMsg('功能不存在，请联系管理员');
        }
        if (1 == $_auth['status']) {
            Util::config('log') && Model::insert('log', ['author' => $this->user['username'], 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '拒绝访问', 'message' => '功能被禁用', 'ip' => $ip, 'status' => 1, 'time' => time()]);
            Util::errMsg('功能被禁用，请联系管理员');
        }
        $_auth_ids = (array)json_decode($_role['auth_ids'], true);
        if (!in_array($_auth['id'], $_auth_ids)) {
            Util::config('log') && Model::insert('log', ['author' => $this->user['username'], 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => '拒绝访问', 'message' => '没有权限', 'ip' => $ip, 'status' => 1, 'time' => time()]);
            Util::errMsg('没有权限，请联系管理员');
        }
        $_role['auth_ids'] = $_auth_ids;
        $this->user['role'] = $_role;
        $this->user['auth'] = $_auth;
        View::assign('site_url', $this->site_url);
        View::assign(['module' => $this->module, 'controller' => $this->controller, 'action' => $this->action]);
    }

    // 继承方法
    // 系统设置
    protected function setting($field = '')
    {
        static $setting;
        $default = [
            'webLogo' => '/static/images/brand.png',
            'webName' => 'Brand',
            'seo_title' => '',
            'seo_description' => '',
            'upload_type' => 'gif|jpg|jpeg|png|mp3|mp4|zip',
            'upload_size' => '2048',
            'robot_index' => '0',
            'alone_login' => '0',
            'copyright' => '&copy; 2021-' . date('Y') . ' Company, Inc.',
            'icp' => 'ICP No.001',
            'cdn_speed' => '0',
            'slide_image_1' => '',
            'slide_url_1' => '',
            'slide_image_2' => '',
            'slide_url_2' => '',
            'slide_image_3' => '',
            'slide_url_3' => '',
            'slide_image_4' => '',
            'slide_url_4' => '',
            'slide_image_5' => '',
            'slide_url_5' => '',
            'hot_num' => '5',
            'comm_num' => '5',
            'related_num' => '3',
            'page_num' => '24',
            'link_num' => 8,
            'voice_read' => '1',
            'can_comment' => '1',
            'pending_comment' => '1',
            'service' => '',
            'email' => '',
            'code' => '',
            'static' => '',
            'date' => '',
            'site' => '',
        ];
        if ($field == 'default')
            return $default;
        if ($setting === null) {
            $setting = Model::fetch('SELECT * FROM `setting` WHERE id=:id', [':id' => 1]);
            if ($setting) {
                $setting = json_decode($setting['value'], true);
                $setting = array_intersect_key($setting, $default);
                $setting = array_merge($default, $setting);
            } else {
                $setting = $default;
            }
        }
        foreach ($setting as $key => $value) {
            if (!empty($value) && substr($value, 0, 1) == '/' && preg_match('#(/static/[^\.]+\.(gif|jpe?g|png|bmp|webp|psd|svg|tiff))#i', $value, $match)) {
                $setting[$key] = $this->subdir . $match[1];
            }
        }
        if ($field)
            return $setting[$field];
        return $setting;
    }

    // 格式化树
    protected function format_tree($data, $field = 'name')
    {
        $data = Util::trees($data);
        $data = array_map(function ($item) use ($field) {
            $item['tree_' . $field] = $item['level'] ? str_repeat("&nbsp;&nbsp;&nbsp;", $item['level']) . "┠ " . $item[$field] : $item[$field];
            return $item;
        }, $data);
        return $data;
    }

    // 媒体图标
    protected function ico($ext)
    {
        $ico = ['ai', 'dir', 'fonts', 'mm', 'pages', 'txt', 'zip', 'apk', 'doc', 'ipa', 'mmap', 'pdf', 'visio', 'bt', 'eps', 'keynote', 'mp3', 'ppt', 'web', 'cad', 'exe', 'links', 'mp4', 'ps', 'xls', 'code', 'fla', 'misc', 'number', 'rar', 'xmind'];
        if (in_array($ext, $ico)) {
            if (is_file(IA_ROOT . '/static/res/layui_exts/ico/' . $ext . '.png')) {
                return $this->site_url . '/static/res/layui_exts/ico/' . $ext . '.png';
            }
        }
        return '';
    }

    // 系统日志
    protected function log($title = '', $message = '', $status = 0)
    {
        Util::config('log') && Model::insert('log', ['author' => $this->user['username'], 'request_method' => Util::requestMethod(), 'url' => htmlentities($_SERVER['REQUEST_URI']), 'title' => $title, 'message' => mb_strimwidth($message, 0, 250, '...', 'UTF-8'), 'ip' => Util::getIp(), 'status' => $status, 'time' => time()]);
    }
}
